package com.app.aipass.fragment.my.paytype.addpaytype;

import android.app.Application;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.app.aipass.app.AppApplication;
import com.app.aipass.data.DemoRepository;
import com.app.aipass.entity.Message;
import com.app.aipass.entity.QiniuToken;
import com.app.aipass.entity.UploadFileEntity;
import com.app.aipass.entity.UserEntity;
import com.app.aipass.http.response.ApiException;
import com.app.aipass.utils.Compressor;
import com.app.aipass.utils.ToastUtil;
import com.app.aipass.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * @author: woking
 * @date: 2021/6/16
 * @description：
 */
public class AddPayTypeViewModel extends BaseViewModel<DemoRepository> {

    public SingleLiveEvent<UploadFileEntity> mUploadFileEntity = new SingleLiveEvent<>();

    private Application mApplication;
    public AddPayTypeViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
        mApplication = application;
    }
    /**
     * 短信验证码
     */
    public void smsCode(TextView send_yzm_tv)
    {
        UserEntity mUserEntity = ((AppApplication)AppApplication.getInstance()).getUserEntity();
        if(mUserEntity == null)
        {
            ToastUtil.showToast("手机号为空");
            return;
        }
        //type:手机验证码类型：1:注册，2:找回密码，3:更换手机号, 4:添加银行卡, 5:设置支付密码,6: 登陆, 11: otc支付, 12: 挂单 用户, 13:挂单 订单
        HashMap<String, Object> map = new HashMap<>();
        map.put("type","11");
        map.put("phone",((AppApplication)AppApplication.getInstance()).getUserEntity().mobile);//挂单数量
        Log.e("TAG",mApplication.toString()+"============smsCode============="+((AppApplication)AppApplication.getInstance()).getUserEntity().mobile);
        model.smsCode(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        Log.e("TAG","============smsCode=====onNext========");
                        if(null != response)
                        {
//                            mPlanIndexEntity.setValue(response.getData());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============smsCode=====onError========");
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShortSafe(ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody));
                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============smsCode=====onComplete========");
                        ToastUtils.showShortSafe("发送成功");
                        send_yzm_tv.setEnabled(false);
//                        send_yzm_tv.setBackgroundResource(R.drawable.shape_d9dade_50);
                        Utils.showCount(send_yzm_tv);
                    }
                });
    }
    public void smsGeneral() {
        Log.e("TAG","==========requestNetWork======otcConfig=======");
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
        HashMap<String, Object> map = new HashMap<>();
//        verify_type=collection&type=mobile
        map.put("lang","zh-cn");
        map.put("verify_type","collection");
        map.put("type","mobile");
        model.smsGeneral(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse response) {
                        if(response.getCode() == 200)
                        {
//                            Log.e("TAG", "=======userInfo================"+response.getData().mobile_hide);
//                            mUserInfoEntity.postValue(response.getData());
                        }
//                        //清除列表
//                        observableList.clear();
//                        //请求成功
//                        if (response.getCode() == 1) {
//                            for (DemoEntity.ItemsEntity entity : response.getResult().getItems()) {
//                                TransactionTabItemViewModel itemViewModel = new TransactionTabItemViewModel(TransactionTabViewModel.this, entity);
//                                //双向绑定动态添加Item
//                                observableList.add(itemViewModel);
//                            }
//                        } else {
//                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShort("数据错误");
//                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","==========requestNetWork======otcConfig===onError==111=="+throwable.getMessage());
                        //关闭对话框
//                        dismissDialog();
//                        //请求刷新完成收回
//                        uc.finishRefreshing.call();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","==========requestNetWork======otcConfig===onComplete====");
                        //关闭对话框
//                        dismissDialog();
                        //请求刷新完成收回
//                        uc.finishRefreshing.call();
                    }
                });
    }
    public void payAccountCreate(int type, HashMap<String, Object> map) {
        Log.e("TAG","==============addOtcPayCccount======type======="+type);
//        HashMap<String, Object> map = new HashMap<>();
//        if(type == 1)//银行卡 {"type": 1,"account": "Entity","name": "Unpro","address": "dsfdsfds","branch": "branch","code": 1234}
//        {
//            map.put("type",1);
//            map.put("account","622161616166161");
//            map.put("name","吕迅");
//            map.put("address","eeeeeeee");
//            map.put("branch","平安支行");
//            map.put("code","88888888");
//        }
//        else if(type == 2)//支付宝
//        {
//            //type=2&account=%E5%8F%AB%E7%9A%84&name=125556&mobile_code=123456&image=c06161148akn4ex.png
//            map.put("lang","zh-cn");
//            map.put("type","2");
//            map.put("name","dddddd");
//            map.put("account","44555552225");
//            map.put("image","sdfsfsf.png");
//            map.put("mobile_code","123456");
//        }
//        else if(type == 3)//微信
//        {
//            //type=3&account=%E6%89%8B%E6%9C%BA%E6%8E%A7&name=%E4%B8%8D%E8%80%83%E8%99%91%E4%BA%86&mobile_code=123456&image=c06161236piskei.png
//            map.put("lang","zh-cn");
//            map.put("type","3");
//            map.put("name","dddddd");
//            map.put("account","44555552225");
//            map.put("image","sdfsfsf.png");
//            map.put("mobile_code","123456");
//        }

        model.addOtcPayCccount(map)//用户和支付方式 来判断唯一性
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        Log.e("TAG","==============addOtcPayCccount======onNext=======");
//                        dismissDialog();
//                        //请求成功
//                        if (response != null)
//                        {
////                            mUpdateCongigEntity.postValue(response.getData());
//                            if(response.getData() == null)
//                            {
//                                ToastUtils.showShort(response.getMessage());
//                            }
//                            else
//                            {
//
//                            }
//                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","==============addOtcPayCccount======onError======="+throwable.getMessage());
                        //关闭对话框
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            ToastUtils.showShort(msg);
                            if(msg.equals("成功"))
                            {
                                RxBus.getDefault().post(new Message("update_pay_type",""));
                            }
                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","==============addOtcPayCccount======onComplete=======");
                        ToastUtils.showShort("添加成功");
                        //关闭对话框
                        dismissDialog();
                        RxBus.getDefault().post(new Message("update_pay_type",""));

                    }
                });
    }
    public void payAccountCreate2(int type) {
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
        HashMap<String, Object> map = new HashMap<>();
        if(type == 1)//银行卡
        {
            map.put("lang","zh-cn");//type=1&name=%E5%93%88&account=44555552225&branch=%E5%B7&address=%E%8A&mobile_code=123456
            map.put("name","dddddd");
            map.put("account","44555552225");
            map.put("branch","sdfsfsf");
            map.put("address","eeeeeeee");
            map.put("mobile_code","123456");
            map.put("type","1");
        }
        else if(type == 2)//支付宝
        {
            //type=2&account=%E5%8F%AB%E7%9A%84&name=125556&mobile_code=123456&image=c06161148akn4ex.png
            map.put("lang","zh-cn");
            map.put("type","2");
            map.put("name","dddddd");
            map.put("account","44555552225");
            map.put("image","sdfsfsf.png");
            map.put("mobile_code","123456");
        }
        else if(type == 3)//微信
        {
            //type=3&account=%E6%89%8B%E6%9C%BA%E6%8E%A7&name=%E4%B8%8D%E8%80%83%E8%99%91%E4%BA%86&mobile_code=123456&image=c06161236piskei.png
            map.put("lang","zh-cn");
            map.put("type","3");
            map.put("name","dddddd");
            map.put("account","44555552225");
            map.put("image","sdfsfsf.png");
            map.put("mobile_code","123456");
        }

        model.payAccountCreate(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse response) {

//                        dismissDialog();
                        //请求成功
                        if (response.getCode() == 200) {
//                            mUpdateCongigEntity.postValue(response.getData());

                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort("数据错误");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }

    public void qiniuToken() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("lang","zh-cn");
        model.qiniuToken(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<QiniuToken>>() {
                    @Override
                    public void onNext(BaseResponse<QiniuToken> response) {
//                        dismissDialog();
                        //请求成功
                        if (response.getCode() == 200) {
//                            mUpdateCongigEntity.postValue(response.getData());
                            Log.e("TAG","==============qiniuToken============="+response.getData().token);
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort("数据错误");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }
    public void uploadFiles(String imgpath)
    {
        File file = new File(imgpath);
        File compressedImage = null;
        if (file.exists()) {
            //压缩文件
            try {
                compressedImage = new Compressor(getApplication()).compressToFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (compressedImage == null) {
                compressedImage = file;
            }

            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), compressedImage);
            MultipartBody.Part part = MultipartBody.Part
//                                .createFormData("key","AAAAA.png")
                                .createFormData("file", file.getName(), requestBody);

            model.uploadFile("image", part)
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog("正在请求...");
                        }
                    })
                    .subscribe(new DisposableObserver<BaseResponse<UploadFileEntity>>() {
                        @Override
                        public void onNext(BaseResponse<UploadFileEntity> response) {
                            Log.e("TAG","==============uploadFiles=======onNext======");

                            if(response != null && response.getData() != null)
                            {
                                mUploadFileEntity.setValue(response.getData());
                            }
                        }
                        @Override
                        public void onError(Throwable throwable) {
                            Log.e("TAG","==============uploadFiles=======onError======"+throwable.getMessage());
                            //关闭对话框
                            dismissDialog();
                            if (throwable instanceof ResponseThrowable) {
                                ToastUtils.showShort(ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody));
                            }
                        }
                        @Override
                        public void onComplete() {
                            Log.e("TAG","==============uploadFiles=====onComplete========");
                            ToastUtils.showShort("上传成功");
                            //关闭对话框
                            dismissDialog();
                        }
                    });
        }
    }
    public void uploadFiles2(String imgpath,String qntoken)
    {
        File file = new File(imgpath);
        File compressedImage = null;
        if (file.exists()) {
            //压缩文件
            try {
                compressedImage = new Compressor(getApplication()).compressToFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (compressedImage == null) {
                compressedImage = file;
            }

            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), compressedImage);
            MultipartBody.Part part = MultipartBody.Part
                    .createFormData("key","AAAAA.png")
                    .createFormData("token",qntoken)
                    .createFormData("file", file.getName(), requestBody);

            HashMap<String, Object> map = new HashMap<>();
            map.put("lang","zh-cn");
            model.uploadFiles("", part)
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog("正在请求...");
                        }
                    })
                    .subscribe(new DisposableObserver<BaseResponse<QiniuToken>>() {
                        @Override
                        public void onNext(BaseResponse<QiniuToken> response) {
//                        dismissDialog();
                            //请求成功
                            if (response.getCode() == 200) {
//                            mUpdateCongigEntity.postValue(response.getData());
                                Log.e("TAG","==============qiniuToken============="+response.getData().token);
                            } else {
                                //code错误时也可以定义Observable回调到View层去处理
                                ToastUtils.showShort("数据错误");
                            }
                        }

                        @Override
                        public void onError(Throwable throwable) {
                            //关闭对话框
                            dismissDialog();
                            if (throwable instanceof ResponseThrowable) {
                                ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            }
                        }

                        @Override
                        public void onComplete() {
                            //关闭对话框
                            dismissDialog();
                        }
                    });
        }


    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
